#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: 即将拥有人鱼线的yjw
   @Time: 2024/4/11 10:50
   @File: env_check.py
   @desc: 判断环境是否正常
"""
import concurrent
import re
from concurrent.futures import ThreadPoolExecutor

from AmlScripts.amlConfig import amlConfig
from DataTest.restartServer.SeeService import SeeService
from CommonScripts.index_rule_cal import indexJobAction
from BladeFerm.utils.http_opration import DingRebot
from DataTest.restartServer.restartServer import restart, checkServerStatus, installServer, logger
from DataTest.util.logCheck import detect_errors
from CommonScripts.blade import python_exec_sql


def change_company(company_no='0', company_name='恒生电子', env=None, ding_url=None):
    """
    反洗钱5.0切换公司号
    :param ding_url:
    :param company_no:
    :param company_name:
    :param env:
    :return: 服务重启结果
    """
    def __clear_and_reset_data(schema, aml_list, sql_reset, env):
        for tableName in aml_list:
            sql = f'truncate  table {schema}.{tableName}'
            python_exec_sql(sql, env=env)
        if re.search(r"pg", env, re.I):
            kwargs = {'schema': f'{schema}'}
            python_exec_sql(sql_reset, env=env, **kwargs)
        else:
            python_exec_sql(sql_reset, env=env)

    # 更新hspbs下的公司号和公司名字，不输入名字默认为恒生电子
    sql = f"UPDATE hspbs.uam_company SET company_no = '{company_no}' , company_name = '{company_name}'"
    logger.info(sql)
    python_exec_sql(sql, env=env)

    # # 删除等级规则，新公司的重新导入
    # amlrc_list = ['amlrc_cfg_category', 'amlrc_cfg_conditionparameter', 'amlrc_cfg_dimensioninfo', 'amlrc_cfg_rule',
    #               'amlrc_cfg_rulecond', 'amlrc_cfg_rulecondinfo','amlrc_cfg_rulescore',
    #               'amlrc_cfg_rulescoreinfo','amlrc_cfg_rulesql']
    # amlre_reset_sql = 'CALL hsamlrc.p_amlrc_init_ruleset()'
    # __clear_and_reset_data('hsamlrc', amlrc_list, amlre_reset_sql, env=env)

    # # 删除CP下的表，新公司的重新导入
    # amlcp_list = []
    # amlcp_reset_sql = "CALL P_AMLCP_RC_INIT_RULESET()"
    # __clear_and_reset_data('hsamlcp', amlcp_list, amlcp_reset_sql, env=env)

    # 删除可疑子项，新公司的重新导入
    amlls_list = ['amlls_cfg_rule', 'amlls_cfg_ruleparameter', 'amlls_cfg_ruleproposal', 'amlls_cfg_rulesql']
    amlls_reset_sql = 'CALL hsamlls.p_amlls_init_ruleset()'
    __clear_and_reset_data('hsamlls', amlls_list, amlls_reset_sql, env=env)

    # 重启pbs-server，com-server,pbs-task服务  aml相关服务会重新部署，其他重启
    server_list = ['pbs-server', 'amlps-server', 'amlcom-server', 'amlcom-ui2']
    amlConfig.update({'env': env})
    try:
        SeeServices = SeeService(amlConfig, timeout=600)
        if SeeServices.get_see_type():
            res_dict = SeeServices.restart_servers(server_list)
            res = SeeServices.judge_restart_result(res_dict)
            amlrc_reset(env=env)
            res_dict_2 = SeeServices.restart_servers(['rcce-task'])
            res2 = SeeServices.judge_restart_result(res_dict_2)
            res = res and res2
        else:
            res = restart('', server_list, env=env)
            amlrc_reset(env=env)
            if res:
                res = restart('', ['rcce-task'], env=env)
            else:
                restart('', ['rcce-task'], env=env)
    except Exception as e:
        logger.error(f"重启服务失败，错误信息：{e}")
        res = False
    if ding_url:
        res_title = '成功' if res else '失败'
        message = f"切换公司号：{company_name} - {company_no} 完成，服务重启结果： {res_title} "
        if not res:
            server_list_str = str(server_list).replace("'", '').replace('"', '')
            message += f"\n服务重启或子项数据导入失败，请按照以下步骤检查："
            message += f"\n[No.1]:检查See平台上{server_list_str}服务状态"
            message += f"\n[No.2]:检查调度任务[p_amlrc_init_ruleset]执行状态"
            message += f"\n[No.3]:检查See平台上[rcce-task]服务状态"
        DingRebot(ding_url).post(message, [], isAtAll=False)


def check_server(env=None):
    """
    检查服务状态，如果服务未运行，重启服务
    :param env:
    :return:
    """
    def __check_server_status(server_list, env_name):
        """
        检查服务状态，如果服务未运行，重启服务。多线程并行执行
        :param server_list:
        :param env_name:
        :return:
        """
        last_result = dict()
        # 创建一个线程池，指定线程数为4
        with ThreadPoolExecutor(max_workers=10) as executor:
            tasks = [executor.submit(checkServerStatus, "url", server, env=env_name) for server in server_list]
            for future in concurrent.futures.as_completed(tasks):
                try:
                    res = future.result()
                    last_result.update(res)
                    logger.debug(f"任务执行结果: {res}")
                except Exception as exc:
                    logger.error(f"任务执行出错: {exc}")
        return last_result
    server_list = [['ZooKeeper', 'RabbitMQ', 'Redis'], 'hsiar', '服务控制台', 'bizframe-cloud-server',
               ['Batch-server', 'wf-server', '离线同步', 'fstore-server',
                'frame-layout', 'bizframe-client', 'subsystem-hui20', 'workflow'],
               'hsrcm-CommonScripts', 'pbs-task', ['pbs-server', 'rcce-task', 'wfl-server', 'pbs-ui', 'messager-server'],
               ['amlps-server', 'amlcom-server', 'amlcrs-server', 'amlcp-server', 'amlwl-server',
                'amlps-ui', 'amlwl-ui', 'amlcom-ui', 'amlcp-ui', 'amlcrs-ui']]
    servers_result = dict()
    amlConfig.update({'env': env})
    SeeServices = SeeService(amlConfig)
    if SeeServices.get_see_type():
        SeeServices.check_server(servers=server_list)
    for keyWord in server_list:
        servers = keyWord if isinstance(keyWord, list) else [keyWord]
        check_result = __check_server_status(servers, env)
        servers_result.update(check_result)
    return servers_result


def check_log(env=None):
    servers = ['hsrcm-pbs-server', 'hsrcm-pbs-task', 'hsrcm-rcce-task', 'hsrcm-amlps-server', 'hsrcm-amlwl-server',
               'hsrcm-amlcom-server']
    for server in servers:
        logger.info(f'============服务{server}的错误日志=============')
        errors = detect_errors(server=server, env=env)
        if '请查询注册中心注册列表' in errors:
            installServer('', 'ZooKeeper', env=env)


def amlrc_reset(env=None):
    input_data = {
        'jobName': '1033808493179465728',
        'jobGroup': 'default',
        'env': env
    }
    indexJobAction(input_data=input_data, ui_expect=None)


def check_env(env=None):
    # 查看错误日志
    check_log(env=env)
    # 第二步   重启服务
    return check_server(env=env)


def on_check_env_complete(status):
    """回调函数，当 check_env 完成时被调用"""
    if status ==1 :
        logger.info(f"环境检查已完成")
    else:
        logger.info(f"公司{status} 切换成功")
